//自调用函数--游戏
(function () {
    var that = null;

    function Game(map) {
        this.food = new Food();
        this.snake = new Snake();
        this.map = map;
    }

    Game.prototype.init = function () {
        that = this;
        this.food.init(this.map);
        this.snake.init(this.map);
        this.snakeRun(this.food, this.map);
        this.bindKey();
    };
    //小蛇移动
    Game.prototype.snakeRun = function (food, map) {
        var timeId = setInterval(function () {
            this.snake.move(food, map);
            this.snake.init(map);
            var maxX = map.offsetWidth / this.snake.width;
            var maxY = map.offsetHeight / this.snake.height;
            var headX = this.snake.body[0].x;
            var headY = this.snake.body[0].y;
            //超过边界
            if (headX < 0 || headX >= maxX || headY < 0 || headY >= maxY) {
                clearInterval(timeId);
                console.log("GAME OVER!")
            }
            //触碰自身
            for (var i = 1; i < this.snake.body.length; i++) {
                var sBody = this.snake.body[i];
                if (headX == sBody.x && headY == sBody.y) {
                    clearInterval(timeId);
                    console.log("DO'NT EAT YOURSELF!")
                }
            }
        }.bind(that), 300)
    };
    //按键监听，改变方向
    Game.prototype.bindKey = function () {
        //改变小蛇移动方向
        document.addEventListener("keydown", function (ev) {
            switch (ev.keyCode) {
                case 37:
                    if (this.snake.direction != "right") {
                        this.snake.direction = "left";
                    }
                    break;
                case 38:
                    if (this.snake.direction != "bottom") {
                        this.snake.direction = "top";
                    }
                    break;
                case 39:
                    if (this.snake.direction != "left") {
                        this.snake.direction = "right";
                    }
                    break;
                case 40:
                    if (this.snake.direction != "top") {
                        this.snake.direction = "bottom";
                    }
                    break;
            }
        }.bind(that), false);
    };
    window.Game = Game;
}());